from django.core.validators import RegexValidator
from django.shortcuts import render, redirect
from django import forms
from web import models
from web.utils.pagination import Pagination

# 用户模块方法
class ScenicModelForm(forms.ModelForm):
    price = forms.IntegerField(
        label="价格",
        validators=[RegexValidator(r'^[0-9]\d?$|0$|100$', '价格需要大于等于0'), ],

    )
    tricknum = forms.IntegerField(
        label="门票数量",
        validators=[RegexValidator(r'^[0-9]\d?$|0$|100$', '门票数量需要大于等于0'), ],
    )
    class Meta:
        model = models.Scenic
        fields = '__all__'
        # widgets = {
        #     "email": forms.EmailInput(attrs={"class": "form-control", "placeholder": "邮箱"}),
        #
        # }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "email":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def mainscenery_list(request):
    """列表"""
    queryset = models.Scenic.objects.filter().all()
    queryset1 = models.Scenic.objects.filter().all().first()
    print(queryset1.image)
    page_object = Pagination(request, queryset)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, "mainscenery_list.html", context)

def mainscenery_listadd(request):
    """ 添加风景（ModelForm版本）"""
    if request.method == "GET":
        form = ScenicModelForm()
        return render(request, 'mainscenery_listadd.html', {"form": form})

    
    form = ScenicModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect('/mainscenery/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'mainscenery_listadd.html', {"form": form})

def mainscenery_listedit(request, nid):
    """ 编辑景点（ModelForm版本）"""
    row_object = models.Scenic.objects.filter(id=nid).first()
    if request.method == "GET":
        # 根据id获取数据，使用form提交数据
        form = ScenicModelForm(instance=row_object)
        return render(request, 'mainscenery_listedit.html', {"form": form})
    # 用户POST提交数据，数据校验。
    form = ScenicModelForm(data=request.POST, instance=row_object, files=request.FILES)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect('/mainscenery/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'mainscenery_listedit.html', {"form": form})

def mainscenery_listdelete(request, nid):
    """ 删除景点（ModelForm版本）"""
    models.Scenic.objects.filter(id=nid).delete()
    return redirect('/mainscenery/list/')
